package pw.hais.helper;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;

/**
 * Created by hais1992 on 2016/1/29/029.
 */
public class BitmapDrawableGCHelper extends BitmapDrawable {
    private int displayResCount = 0;
    private boolean mHasBeenDisplayed;

    public BitmapDrawableGCHelper(Resources res, Bitmap bitmap) {
        super(res, bitmap);
    }


    /**
     * @param isDisplay
     */
    public void setIsDisplayed(boolean isDisplay) {
        synchronized (this) {
            if (isDisplay) {
                mHasBeenDisplayed = true;
                displayResCount++;
            } else {
                displayResCount--;
            }
        }

        checkState();

    }

    /**
     * 检查图片的一些状态，判断是否需要调用recycle
     */
    private synchronized void checkState() {
        if (displayResCount <= 0 && mHasBeenDisplayed && hasValidBitmap()) {
            getBitmap().recycle();
        }
    }


    /**
     * 判断Bitmap是否为空且是否调用过recycle()
     *
     * @return
     */
    private synchronized boolean hasValidBitmap() {
        Bitmap bitmap = getBitmap();
        return bitmap != null && !bitmap.isRecycled();
    }

}

